package com.orderplus.opshop.common.util;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串相关的工具
 *
 * @author sunny
 */
public class StringUtil {
	private StringUtil() {
	}

	/**
	 * 判断字符串是否为 "" || null
	 *
	 * @param str
	 * @return
	 */
	public static boolean isEmpty(String str) {
		return null == str || 0 == str.length();
	}

	/**
	 * toString
	 *
	 * @param str
	 * @return
	 */
	public static String toString(String str) {
		if (null == str) {
			return "";
		}
		return str;
	}

	public static double toDouble(String str, double defaultDouble) {
		if (isEmpty(str)) {
			return defaultDouble;
		}
		try {
			return Double.parseDouble(str);
		} catch (Exception e) {
			return defaultDouble;
		}
	}

	/**
	 * toString
	 *
	 * @param obj
	 * @return
	 */
	public static String toString(Object obj) {
		if (null == obj) {
			return "";
		}
		return obj.toString();
	}

	public static int toInt(String str) {
		if (isEmpty(str)) {
			return 0;
		}
		return Integer.parseInt(str);
	}

	/**
	 * 字符串转成数字
	 *
	 * @param str
	 * @param defaultInt 默认值
	 * @return
	 */
	public static int toInt(String str, int defaultInt) {
		// 如果字串为空时，返回defaultValue
		if (null == str || 0 == str.length()) {
			return defaultInt;
		}

		try {
			char first = str.charAt(0);
			if ('0' == first && str.length() > 2) {
				// 如果是以0x开首表示是十六进制
				first = str.charAt(1);
				if ('x' == first || 'X' == first) {
					return Integer.parseInt(str.substring(2), 16);
				}
			} else if (str.length() > 1 && ('x' == first || 'X' == first)) {
				// x开首以十六进制
				return Integer.parseInt(str.substring(1), 16);
			}
			return Integer.parseInt(str);
		} catch (NumberFormatException e) {
		}
		return defaultInt;
	}

	/**
	 * 判断字符是否为邮箱地址格式
	 *
	 * @param str
	 * @return
	 */
	public static boolean isEmail(String str) {
		if (isEmpty(str)) {
			return false;
		}
		String regex = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,5}$";
		return str.matches(regex);
	}

	/**
	 * Description: 将字符串表达式转换成map       expr = "Y:是|N:否|-1:删除|0:正常"
	 *
	 * @author: ronghua
	 * @date: 2014年11月20日上午10:32:48
	 */
	public static Map<String, String> toMap(String expr) {
		if (isEmpty(expr)) {
			return null;
		}
		Map<String, String> map = new HashMap<String, String>();
		String[] arr = expr.trim().split("\\|");
		for (String str : arr) {
			String[] kv = str.split(":");
			map.put(kv[0], kv[1]);
		}
		return map;
	}

	public static List<Map<?, ?>> toList(String expr) {
		if (isEmpty(expr)) {
			return null;
		}
		List<Map<?, ?>> list = new ArrayList<Map<?, ?>>();
		String[] arr = expr.trim().split("\\|");
		Map<String, String> map = null;
		for (String str : arr) {
			String[] kv = str.split(":");
			map = new HashMap<String, String>();
			map.put("code", kv[0]);
			map.put("desc", kv[1]);
			list.add(map);
		}

		return list;
	}

	public static List<String> toList(String str, char separatorChar) {
		return splitWorker(str, separatorChar, false);
	}

	private static List<String> splitWorker(String str, char separatorChar, boolean preserveAllTokens) {
		if (str == null) {
			return null;
		}
		int len = str.length();
		if (len == 0) {
			return new ArrayList<String>();
		}
		List<String> list = new ArrayList<String>();
		int i = 0;
		int start = 0;
		boolean match = false;
		boolean lastMatch = false;
		while (i < len) {
			if (str.charAt(i) == separatorChar) {
				if ((match) || (preserveAllTokens)) {
					list.add(str.substring(start, i));
					match = false;
					lastMatch = true;
				}
				start = ++i;
			}

			lastMatch = false;
			match = true;
			++i;
		}
		if ((match) || ((preserveAllTokens) && (lastMatch))) {
			list.add(str.substring(start, i));
		}
		return list;
	}

	//传入的CharSequence是String的接口，同样StringBuffer这些也是，可适用这里。Sequence的英语是序列的意思。  
	public static boolean isBlank(CharSequence cs) {
		//标记字符长度，
		int strLen;
		//字符串不存在或者长度为0
		if (cs == null || (strLen = cs.length()) == 0) {
			return true;
		}
		for (int i = 0; i < strLen; i++) {
			//判断空格，回车，换行等，如果有一个不是上述字符，就返回false
			if (Character.isWhitespace(cs.charAt(i)) == false) {
				return false;
			}
		}
		return true;
	}

	//这个是isNotBlank()  
	public static boolean isNotBlank(CharSequence cs) {
		return !StringUtil.isBlank(cs);
	}

	/**
	 * Description: 去除字符串最后一个逗号
	 *
	 * @author: ronghua
	 * @date: 2016年11月22日下午2:27:57
	 */
	public static String removeLastComma(String str) {
		if (isBlank(str)) {
			return str;
		} else {
			return str.endsWith(",") ? str.substring(0, str.length() - 1) : str;
		}
	}


	/**
	 * oldStr 源字符串
	 * splitStr 进行处理的字符分隔符
	 * 如 "aa,bb,cc"转换成为"'aa','bb','cc'"
	 ***/
	public static final String getGenerateSplit(String oldStr) {
		return getGenerateSplit(oldStr, ",");
	}

	/**
	 * oldStr 源字符串
	 * splitStr 进行处理的字符分隔符
	 * 如 "aa,bb,cc"转换成为"'aa','bb','cc'"
	 ***/
	public static final String getGenerateSplit(String oldStr, String splitStr) {
		String returnStr = "";
		if (isNotBlank(oldStr)) {
			if (oldStr.indexOf("'") == 0) {
				return oldStr;
			}
			String[] checkArray = oldStr.split(splitStr);
			for (int i = 0; i < checkArray.length; i++) {
				if (i == 0) {
					returnStr = "'" + checkArray[i] + "'";
				} else {
					returnStr += "," + "'" + checkArray[i] + "'";
				}
			}
		}
		return returnStr;
	}

	/**
	 * Description: 去除特殊符号（!!！？？!!!!%*）%,，。!!..**）
	 *
	 * @author: 温俊业
	 * @date: 2014年11月20日上午10:32:48
	 */
	public static final String removeSign(String str) {

		str = str.replaceAll("[\\pP\\p{Punct}]", "");

		return str;

	}

	/**
	 * 比较字符串，字符串entirely中是否包含query字符串
	 *
	 * @param entirely
	 * @param query
	 * @return
	 * @author maihj
	 */
	public static boolean matches(String entirely, String query) {

		return entirely.matches(".*" + query + ".*");
	}

	/**
	 * 缩略字符串（不区分中英文字符）
	 *
	 * @param str    目标字符串
	 * @param length 截取长度
	 * @return
	 */
	public static String abbr(String str, int length) {
		if (str == null) {
			return "";
		}
		try {
			StringBuilder sb = new StringBuilder();
			int currentLength = 0;
			for (char c : replaceHtml(StringEscapeUtils.unescapeHtml4(str)).toCharArray()) {
				currentLength += String.valueOf(c).getBytes("GBK").length;
				if (currentLength <= length - 3) {
					sb.append(c);
				} else {
					sb.append("...");
					break;
				}
			}
			return sb.toString();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 替换掉HTML标签方法
	 */
	public static String replaceHtml(String html) {
		if (isBlank(html)) {
			return "";
		}
		String regEx = "<.+?>";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(html);
		String s = m.replaceAll("");
		return s;
	}

	//去除空格 回车 换行
	public static String removeBlank(String str) {
		if (!ValueUtil.isEmpty(str)) {
			return str.replaceAll(RegularUtil.SERIAL_CODE, "");
		}
		return "";
	}

	public static boolean isLetter(char c) {
		int k = 0x80;
		return c / k == 0 ? true : false;
	}

	/**
	 * 得到一个字符串的长度,显示的长度,一个汉字或日韩文长度为2,英文字符长度为1
	 *
	 * @param s 需要得到长度的字符串
	 * @return int 得到的字符串长度
	 */
	public static int length(String s) {
		if (s == null) {
			return 0;
		}
		char[] c = s.toCharArray();
		int len = 0;
		for (int i = 0; i < c.length; i++) {
			len++;
			if (!isLetter(c[i])) {
				len++;
			}
		}
		return len;
	}

	private static Pattern NUMBER_PATTERN = Pattern.compile(".*\\d+.*");

	/**
	 * 判断一个字符串是否含有数字
	 *
	 * @param str
	 * @return
	 */
	public static boolean hasDigit(String str) {
		boolean flag = false;
		Pattern p = NUMBER_PATTERN;
		Matcher m = p.matcher(str);
		if (m.matches()) {
			flag = true;
		}
		return flag;
	}


	/**
	 * inputStr 源字符串
	 * 如 "["aa","bb","cc"]"转换成为字符串数组
	 ***/
	public static String[] toStrArray(String inputStr) {
		inputStr = inputStr.replace("[","");
		inputStr = inputStr.replace("]","");
		inputStr = inputStr.replaceAll("\"","");

		String[] arrayStr = StringUtils.split(inputStr,",");

//		System.out.println(arrayStr);
		return arrayStr;
	}


	public static void main(String[] args) {
		// String str = "sunny";
		// String em = "suse33dq@q3qee.comdse";
		// _Logger.info("" + isEmail(em));

		// 533c5ba8368075db8f6ef201546bd71a
		//System.out.println(toMap("hh:1|tt:2"));
//		String str = "123 ,23423 ";
//		System.out.println(StringUtils.trimAllWhitespace(str));
//		List<String> l = StringUtil.toList(str, ',');
//		System.out.println(l);
//		boolean b = StringUtil.isNotBlank(str);
		//System.out.println(new BigDecimal(0.43000).divide(new BigDecimal(0.46),10,BigDecimal.ROUND_HALF_DOWN));
//		String str = "123,3423,";
//		System.out.println(str.endsWith(","));
//		System.out.println(str.substring(0, str.length() - 1));
//		System.out.println(removeLastComma(","));

//		String str1 = "hello你好大";
//		System.out.println(length(str1));
		toStrArray("[\"http://img.alicdn.com/bao/uploaded/i4/2652292790/O1CN01Mqcjjp1WTrVTrPf9W_!!2652292790.jpg\",\"http://img.alicdn.com/bao/uploaded/i3/2652292790/O1CN01sWXkKZ1WTrVuEifps_!!2652292790.jpg\",\"http://img.alicdn.com/bao/uploaded/i1/2652292790/O1CN01QL38ib1WTrVUtxpIQ_!!2652292790.jpg\",\"http://img.alicdn.com/bao/uploaded/i2/2652292790/O1CN015cn8kt1WTrVxWdKWB_!!2652292790.jpg\",\"http://img.alicdn.com/bao/uploaded/i2/2652292790/O1CN01HXA2Wi1WTrVWA6rRG_!!2652292790.jpg\"]");
	}

}
